package com.rati.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rati.usercenter.common.SelectType;
import com.rati.usercenter.constant.UserConstant;
import com.rati.usercenter.exception.BusinessException;
import com.rati.usercenter.model.DTO.UserInfoDTO;
import com.rati.usercenter.model.VO.UserVO;
import com.rati.usercenter.model.domain.User;
import com.rati.usercenter.service.UserService;
import com.rati.usercenter.mapper.UserMapper;
import com.rati.usercenter.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.rati.usercenter.constant.UserConstant.*;
import static com.rati.usercenter.common.ErrorCode.*;

/**
 * @author Lwh
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2022-12-11 20:14:07
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "rate";

    /**
     * <pre>
     * 注册逻辑
     * 1. 用户在前端输入账号、密码以及校验码
     * 2. 校验数据
     *   (1) 非空
     *   (2) 账户（6~20位，字母开头，可包含字母、数字、-、_，不含特殊字符）
     *   (3) 密码（6~位）
     *   (4) 账户不能重复
     *   (5) 密码和校验码相同
     * 3. 对密码进行加密
     * 4. 向数据库中插入用户数据
     * </pre>
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码（二次输入）
     * @return 新用户id
     */
    @Override
    public long userRegistry(String userAccount, String userPassword, String checkPassword) {
//        1. 数据校验
//        非空及长度校验
        if (userAccount.length() < 6 || userPassword.length() < 6 || checkPassword.length() < 6 ||
                StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(PARAMS_ERROR, "账户密码过短或请求参数含空");
        }
//        账户格式校验
        final String validAccountPattern = "^[a-zA-Z][-_a-zA-Z0-9]{5,19}$";
        if (!Pattern.matches(validAccountPattern, userAccount)) {
            throw new BusinessException(PARAMS_ERROR, "非法账户格式");
        }
//        密码格式校验
//        final String validStrongPasswordPattern = "\t^.*(?=.{6,})(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@\\.#$%^&*? ]).*$";
//        final String validWeakPasswordPattern = "\t^[\\w]{6,16}$";
//        if (!Pattern.matches(validWeakPasswordPattern, userPassword)) {
//            return -1;
//        }
//        校验密码
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(PARAMS_ERROR, "两次输入密码不一致");
        }
//        账户不能重复
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account", userAccount);
        long count = userMapper.selectCount(wrapper);
        if (count != 0) {
            throw new BusinessException(PARAMS_ERROR, "账户重复");
        }

//        2. 加密密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

//        3. 向数据库插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(SERVER_ERROR, "插入用户失败");
        }
        return user.getId();
    }

    /**
     * <pre>
     * 登录逻辑
     * 1. 校验输入数据
     *   (1) 非空
     *   (2) 账户6-20位，不包含特殊字符
     *   (3) 密码6位以上
     * 2. 校验密码是否输入正确
     * 3. 记录用户登录态（使用SpringBoot封装的服务器tomcat）
     * 4. 返回用户信息（脱敏）
     * </pre>
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return 脱敏后的用户信息
     */
    @Override
    public UserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
//        1. 数据校验
        if (userAccount.length() < 6 || userPassword.length() < 6 ||
                StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(PARAMS_ERROR, "账户密码过短或请求参数含空");
        }
//        账户格式校验
        final String validAccountPattern = "^[a-zA-Z][-_a-zA-Z0-9]{5,19}$";
        if (!Pattern.matches(validAccountPattern, userAccount)) {
            throw new BusinessException(PARAMS_ERROR, "非法账户格式");
        }
//        2. 加密密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
//        3. 查询用户（处理逻辑删除）
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account", userAccount);
        wrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(wrapper);
//        用户不存在
        if (user == null) {
            log.info("user log failed. userAccount cannot match userPassword");
            throw new BusinessException(NULL_ERROR, "账户密码不匹配");
        }
//        4. 用户脱敏
        UserVO safetyUser = getSafetyUser(user);
//        5. 记录用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    /**
     * 用户登出
     *
     * @return 登出标识
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
//        清除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 获取当前登录的用户信息
     */
    @Override
    public UserVO getCurrentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(PARAMS_ERROR, "请求为空");
        }
        UserVO loginUser = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser == null) {
            throw new BusinessException(NO_LOGIN, "用户未登录");
        }
//        查数据库已获取用户最新信息
        User currentUser = this.getById(loginUser.getId());
        if (currentUser == null) {
            throw new BusinessException(NULL_ERROR, "查询用户不存在");
        }
//        判断用户当前状态是否正常
        if (this.abnormalStatus(currentUser)) {
            throw new BusinessException(ABNORMAL_STATUS, "该用户当前状态异常");
        }
//        脱敏
        return this.getSafetyUser(currentUser);
    }

    /**
     * 根据标签查询用户
     *
     * @param tagNameList 用户需要含有的标签
     * @param flag        查询标志符
     * @return 符合要求的用户列表
     */
    @Override
    public List<UserVO> searchByTags(List<String> tagNameList, SelectType flag) {
        if (tagNameList.isEmpty()) {
            throw new BusinessException(PARAMS_ERROR, "标签列表不能为空");
        }
        if (flag == null) {
            throw new BusinessException(PARAMS_ERROR, "查询标志符有误");
        }
        List<User> userList;
        switch (flag) {
            case ALL_MATCH: {
//                要求全部匹配，拼接tag
                QueryWrapper<User> wrapper = new QueryWrapper<>();
                for (String tag : tagNameList) {
                    wrapper = wrapper.like("tags", tag);
                }
                userList = userMapper.selectList(wrapper);
                break;
            }
            case PARTIAL_MATCH: {
//                部分匹配即可
                userList = userMapper.getOrByTags(tagNameList);
                break;
            }
            default: {
                throw new BusinessException(PARAMS_ERROR, "查询标志符有误");
            }
        }
        if (userList.isEmpty()) {
            throw new BusinessException(NULL_ERROR, "无符合要求的用户");
        }
//        用户脱敏
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 更新用户信息
     *
     * @param user      新用户信息
     * @param loginUser 当前登录的用户
     * @return 更新结果
     */
    @Override
    public int updateUser(UserInfoDTO user, UserVO loginUser) {
        if (user.getId() < 1) {
            throw new BusinessException(PARAMS_ERROR, "传入非法用户id值");
        }
        if (!Objects.equals(loginUser.getId(), user.getId())) {
            throw new BusinessException(NO_AUTH, "无权修改该用户的信息");
        }
        if (StringUtils.isAllEmpty(user.getUsername(), user.getEmail(), user.getPhone(), user.getAvatarUrl())) {
            throw new BusinessException(PARAMS_ERROR, "无需要修改的字段");
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setUsername(user.getUsername());
        newUser.setPhone(user.getPhone());
        newUser.setEmail(user.getEmail());
        newUser.setAvatarUrl(user.getAvatarUrl());
        return userMapper.updateById(newUser);
    }

    /**
     * 按照标签相似度匹配用户
     * 查询当前用户匹配度最高的前几名用户
     *
     * @param num         需要的匹配用户数量
     * @param currentUser 当前登录用户
     * @return 匹配用户列表
     */
    @Override
    public List<UserVO> getMatchUsers(long num, UserVO currentUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = currentUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
//        依次计算所有用户和当前用户的相似度
        for (User user : userList) {
            String userTags = user.getTags();
//            无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), currentUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
//            计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
//        按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
//        排好序的 userId 列表
        List<Long> userIdList = topUserPairList.stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
//        将包含在列表中的用户查出，按id分组
        Map<Long, List<UserVO>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(this::getSafetyUser)
                .collect(Collectors.groupingBy(UserVO::getId));
//        按照原id的顺序取出用户
        List<UserVO> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }


    /**
     * 用户脱敏
     */
    @Override
    public UserVO getSafetyUser(User user) {
        if (user == null) {
            return null;
        }
        UserVO safetyUser = new UserVO();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setTags(user.getTags());
        safetyUser.setUserStatus(user.getUserStatus());
        return safetyUser;
    }

    /**
     * 是否为管理员
     */
    @Override
    public boolean isNotAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user == null || !user.getUserStatus().equals(ADMIN_ROLE);
    }

    @Override
    public boolean isNotAdmin(UserVO userVO) {
        return userVO == null || !userVO.getUserStatus().equals(ADMIN_ROLE);
    }

    /**
     * TODO
     * 判断用户是否存在异常状态
     */
    @Override
    public boolean abnormalStatus(User user) {
        return false;
    }

    /**
     * 判断某个用户是否拥有某些或全部的给定标签
     *
     * @param tagNameList 给定的标签列表
     * @param user        需判断的用户
     * @param flag        查询标志符
     * @return 是否符合要求
     */
    @Override
    public boolean isIncludeTags(List<String> tagNameList, User user, SelectType flag) {
        Gson gson = new Gson();
        Set<String> userTagSet = gson.fromJson(user.getTags(), new TypeToken<Set<String>>() {
        }.getType());
        if (userTagSet.isEmpty()) {
            return false;
        }
        switch (flag) {
//            userTagSet需要包含tagNameList中的每一项
            case ALL_MATCH: {
                for (String tag : tagNameList) {
                    if (!userTagSet.contains(tag)) {
                        return false;
                    }
                }
                return true;
            }
//            userTagSet只需要包含tagNameList中的一项即可
            case PARTIAL_MATCH: {
                for (String tag : tagNameList) {
                    if (userTagSet.contains(tag)) {
                        return true;
                    }
                }
                return false;
            }
            default: {
                throw new BusinessException(PARAMS_ERROR, "查询标志符有误");
            }
        }
    }

}




